#!/bin/sh

if [ ! -e /var/lib/mender/mender-agent.pem ]; then
    # Normally Mender will create the private key on startup if it doesn't exist.
    # This script is used to manually create the key outside of the Mender client.
    #
    # This is invoked by systemd as an ExecStartPre step for Mender.
    #
    # This is to allow proper sequencing of initialization steps with the Google
    # Cloud integration as both Mender and GCP are sharing the same key. We have
    # a state script to disallow Mender server connections until the GCP setup
    # for preauthorization has completed. If we allow the normal client initialization
    # to generate the certificate, then it will be too late for GCP.
    #
    cd /tmp
    /usr/sbin/mender-keygen-client > /dev/null
    mv keys-client-generated/private.key /var/lib/mender/mender-agent.pem
    openssl rsa -in /var/lib/mender/mender-agent.pem -pubout  -out /var/lib/mender/rsa_public.pem
    chmod 600 /var/lib/mender/mender-agent.pem /var/lib/mender/rsa_public.pem
    rm -rf keys-client-generated/
fi
